<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.text.DateFormat" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.time.LocalDate" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Set" %>
<%@ page import="java.util.HashSet" %>
<%@ page import="org.apache.commons.lang.StringUtils" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.engine.hikvision.utils.HikVisionApiUtil" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="com.alibaba.fastjson.JSON" %>
<%@ page import="com.alibaba.fastjson.JSONArray" %>
<%@ page import="com.weaver.general.Util" %>
<%@ page import="org.hsqldb.lib.StringUtil" %>
<%@ page import="java.util.UUID" %>
<%@ page import="com.mzlion.core.lang.CollectionUtils" %>
<%@ page import="weaver.formmode.setup.ModeRightInfo" %>
<%@ page import="com.huawei.shade.org.joda.time.format.DateTimeFormatter" %>
<%@ page import="com.huawei.shade.org.joda.time.format.DateTimeFormat" %>
<%@ page import="com.huawei.shade.org.joda.time.DateTime" %><%
    BaseBean baseBean = new BaseBean();
    out.println("begin do SyncCanteenDoorDataJob invoke ...");
    try {
        RecordSet rs = new RecordSet();
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = dateFormat.format(date);
        String startTime = "";
        String endTime = format + "T23:59:59+08:00";

        // 同步所有人近七天的数据
        LocalDate currentDate = LocalDate.now();
        // 获取前七天的日期
        LocalDate previousDate = currentDate.minusDays(2);
        LocalDate toDate = currentDate.plusDays(1);
        LocalDate tempDate = currentDate.minusDays(30);
        java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = previousDate.format(formatter);
        String tempDateStr = tempDate.format(formatter);
        String toDateStr = toDate.format(formatter);
        startTime = formattedDate + "T00:00:01+08:00";

        Map<String, String> certNoAndIdMap = new HashMap<>();
        Map<String, String> idAndDeptMap = new HashMap<>();
        Map<String, String> idAndComMap = new HashMap<>();
        rs.execute("select id, workcode, departmentid, SUBCOMPANYID1 from hrmresource");
        while (rs.next()) {
            String id = rs.getString("id");
            String workcode = rs.getString("workcode");
            String departmentid = rs.getString("departmentid");
            String fb = rs.getString("SUBCOMPANYID1");
            certNoAndIdMap.put(workcode, id);
            idAndDeptMap.put(id, departmentid);
            idAndComMap.put(id, fb);
        }
        String sql = "select * from uf_stdkjcsjb where dkrq between '" + tempDateStr + "' and '" + toDateStr + "'";
        out.println("SyncCanteenDoorDataJob sql is:" + sql);
        rs.execute(sql);
        Set<String> keySet = new HashSet<>();
        while (rs.next()) {
            String gh = rs.getString("gh");
            String dkrq = rs.getString("dkrq");
            String dksj = rs.getString("dksj");
            String kjxx = rs.getString("kjxx");
            String key = gh + "-" + dkrq + "-" + dksj + "-" + kjxx;
            keySet.add(key);
        }

        String doorIndexCodeStr = baseBean.getPropValue("hikvisiondoorindexcode", "CANTEEN_DOOR_INDEX_CODES");
        String workCodePrefixStr = baseBean.getPropValue("hikvisiondoorindexcode", "WORK_CODE_PREFIX");
        String[] doorIndexCodes = null;

        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");

        Map<java.lang.String, Object> map = new HashMap<>();
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("pageSize", "1000");

        DateTimeFormatter dtf1 = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ");

        DateTimeFormatter dtf2= DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

        if (StringUtils.isNotEmpty(doorIndexCodeStr)) {
            doorIndexCodes = doorIndexCodeStr.split(",");
            for (String s : doorIndexCodes) {
                int pageNo = 1;
                boolean isGoing = true;
                List<String> tempIndexCodes = new ArrayList<>();
                tempIndexCodes.add(s);
                map.put("doorIndexCodes", tempIndexCodes.toArray());
                while (isGoing) {
                    try {
                        map.put("pageNo", String.valueOf(pageNo));
                        out.println("SyncCanteenDoorDataJob map:" + map);
                        String result = HikVisionApiUtil.callPostApiList("/api/acs/v2/door/events", map);
                        JSONObject obj = JSON.parseObject(result);
                        JSONObject dataObj = obj.getJSONObject("data");
                        JSONArray jsonList = dataObj.getJSONArray("list");
                        if (dataObj.getInteger("totalPage") > pageNo) {
                            pageNo += 1;
                        } else {
                            isGoing = false;
                        }
                        out.println("jsonList size:" + jsonList.size());
                        List<List> insertParams = new ArrayList<>();
                        for (int i = 0; i < jsonList.size(); i++) {
                            JSONObject jsonObject = jsonList.getJSONObject(i);
                            String certNo = Util.null2String(jsonObject.getString("jobNo"));
                            if (StringUtil.isEmpty(certNo)) {
                                continue;
                            }
                            if (org.apache.commons.lang3.StringUtils.isNotEmpty(workCodePrefixStr) && !certNo.startsWith(workCodePrefixStr)) {
                                continue;
                            }
                            String userId = certNoAndIdMap.get(certNo);
                            String eventTime = jsonObject.getString("eventTime");
                            DateTime dt= dtf1.parseDateTime(eventTime);
                            String[] arr = dt.toString(dtf2).split("\\s+");
                            String signDate = arr[0];
                            String signTime = arr[1];
                            String signFrom = jsonObject.getString("doorName");

                            String keyTemp = certNo + signDate + signTime + signFrom;
                            if ((!org.springframework.util.CollectionUtils.isEmpty(keySet)) && keySet.contains(keyTemp)) {
                                continue;
                            }

                            String bm = idAndDeptMap.get(userId);
                            String fb = idAndComMap.get(userId);
                            String nowDate = sdfDate.format(new Date());
                            String nowTime = sdfTime.format(new Date());

                            List insertParam = new ArrayList<>();
                            insertParam.add(userId);
                            insertParam.add(certNo);
                            insertParam.add(signDate);
                            insertParam.add(signTime);
                            insertParam.add(signFrom);
                            insertParam.add(16);
//                            insertParam.add(UUID.randomUUID());
                            insertParam.add(1);
                            insertParam.add(0);
                            insertParam.add(nowDate);
                            insertParam.add(nowTime);
                            insertParam.add(0);
                            insertParam.add(bm);
                            insertParam.add(fb);
                            insertParams.add(insertParam);
                        }

                        if (CollectionUtils.isNotEmpty(insertParams)) {
                            String insertSql = "INSERT INTO uf_stdkjcsjb (xm, gh, dkrq, dksj, kjxx, formmodeid, " +
                                    "modedatacreater,modedatacreatertype, modedatacreatedate, modedatacreatetime, ytj, bm, fb) VALUES " +
                                    "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                            rs.executeBatchSql(insertSql, insertParams);
                        }
                    } catch (Exception e) {
                        isGoing = false;
                        out.println("SyncCanteenDoorDataJob error:" + e.getMessage());
                    }
                }
            }
        }

        // 统计食堂打卡信息
//        handleCanteenCnt();

        // 权限重构
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(1, 16, 23);
    } catch (Exception e) {
        out.println("SyncCanteenDoorDataJob error:" + e);
    }
    out.println("a end do SyncCanteenDoorDataJob invoke...");
%>